import * as BestEffortJsonParser from 'best-effort-json-parser';

const bestEffortParse =
  (BestEffortJsonParser && (BestEffortJsonParser.parse || BestEffortJsonParser.default)) ||
  ((input) => JSON.parse(input));

const CODEBLOCK_REGEX = /```(?:json)?\s*([\s\S]*?)\s*```/gi;

const collectToolCalls = (node, results) => {
  if (!node || typeof node !== 'object') {
    return;
  }

  if (Array.isArray(node)) {
    results.push(...node);
  }

  if (Array.isArray(node.tool_calls)) {
    results.push(...node.tool_calls);
  }

  if (Array.isArray(node.plan?.tool_calls)) {
    results.push(...node.plan.tool_calls);
  }

  if (Array.isArray(node.plan)) {
    results.push(...node.plan);
  }

  if (Array.isArray(node.message?.tool_calls)) {
    results.push(...node.message.tool_calls);
  }
};

const collectJsonCandidates = (value) => {
  const candidates = [];
  let match;

  while ((match = CODEBLOCK_REGEX.exec(value)) !== null) {
    if (match[1]) {
      candidates.push(match[1]);
    }
  }

  return candidates;
};

const safeParseJson = (candidate) => {
  if (!candidate) {
    return null;
  }

  const cleaned = candidate
    .trim()
    .replace(/^```(?:json)?\s*/i, '')
    .replace(/```$/i, '')
    .replace(/,\s*(?=[}\]])/g, '')
    .replace(/\/\*[\s\S]*?\*\//g, '')
    .replace(/(^|[^:])\/\/.*$/gm, '$1')
    .trim();

  if (!cleaned) {
    return null;
  }

  try {
    return bestEffortParse(cleaned);
  } catch (error) {
    console.log('[ToolCallUtils] JSON 解析失败，跳过候选:', error.message);
    return null;
  }
};

export function extractToolCallsFromText(response = '') {
  if (!response || typeof response !== 'string') {
    return [];
  }

  const text = response.trim();
  if (!text) {
    return [];
  }

  console.log('[ToolCallUtils] 尝试解析工具调用，长度:', text.length);

  const candidates = collectJsonCandidates(text);

  for (const candidate of candidates) {
    const parsed = safeParseJson(candidate);
    if (!parsed) {
      continue;
    }

    const calls = [];
    collectToolCalls(parsed, calls);
    if (calls.length) {
      console.log('[ToolCallUtils] 提取到工具调用:', calls);
      return calls;
    }
  }

  console.log('[ToolCallUtils] 未检测到工具调用');
  return [];
}
